<template>
  <div>
      <Spin fix v-if="loading"></Spin>
      <div class="contentBox">
        <div class="contentBox-left">
            <Form ref="formValidate" style="justify-content: start;height: 100px;" :model="ingredientsForm">
              <FormItem label="食材名称:" prop="mealMaterialName" style="margin-right: 20px" :label-width="80">
                <Input v-model="ingredientsForm.mealMaterialName" maxlength="20" clearable placeholder="请输入食材名称"
                  style="width: 100px">
                </Input>
              </FormItem>
              <FormItem label="状态:" prop="type" :label-width="50" style="margin-right: 20px">
                <Select v-model="ingredientsForm.type" style="width: 100px" placeholder="请选择状态" clearable>
                  <Option :value="-1">全部</Option>
                  <Option :value="1">已匹配</Option>
                  <Option :value="0">未匹配</Option>
                </Select>
              </FormItem>
              <FormItem label="食材类型:" prop="foodClass" :label-width="80" style="margin-right: 20px">
                <Select v-model="ingredientsForm.foodClass" style="width: 100px" placeholder="请选择状态" clearable>
                  <Option
                :value="item.name"
                v-for="(item, index) in materialTypeList"
                :key="index"
                >{{ item.name }}</Option
              >
                 
                </Select>
              </FormItem>
              <Button class="ml_24" type="primary" @click="
                pages.page = 1;
              selectMealFoodOrPurchaseFoodMatchingApi();
              ">查询</Button>
            </Form>
            <h4>食材列表</h4>
            <cus-table border :loading="loading" :columns="columns" :data="ingredientsData" :bottomClass="['cus-page','bottomButton']" :index="2" :highlightRow="true" @onCurrentChange="onCurrentChange" >
            </cus-table>
            <div style="width: 100%; text-align: right">
              <cus-page :data="pages" class="mt_10" @pageChange="selectMealFoodOrPurchaseFoodMatchingApi()"
                :showSizer="false" :showElevator="false"></cus-page>
            </div>
         
        </div>
        <div class="contentBox-center" >
          <Form ref="formValidate" :model="noBindProductForm" style="height: 100px;">
              <FormItem label="商品名称" prop="materialName" :label-width="80" style="margin-right: 20px">
                <Input v-model="noBindProductForm.materialName" maxlength="20" clearable placeholder="请输入商品名" style="width: 150px">
                </Input>
              </FormItem>
              <FormItem label="商品类型:" prop="productCategoryId" :label-width="80" style="margin-right: 20px">
                <Select v-model="noBindProductForm.productCategoryId" style="width: 150px" placeholder="请选择状态" clearable>
                  <Option
                :value="item.id"
                v-for="(item, index) in productcategoryList"
                :key="index"
                >{{ item.categoryName }}</Option
              >
                </Select>
              </FormItem>
              
              <Button class="mr_20 mb_20" type="primary" @click="
                pages2.page = 1;
              selectProductMaterialListApi();
              ">查询</Button>
            </Form>
          
            <h4>待匹配列表</h4>
            <cus-table border :loading="loading2" :columns="columns2" :data="productList" :bottomClass="['cus-page','bottomButton']" :index="2">
              <template slot-scope="{ row }" slot="operation">
                            <div class="flex">
                   <cus-button
                type="text"
                size="small"
              
                :style="{ color: '#1E6FFF', padding: '0 8px' }"
                @onClick="onMatching(row)"
              >
                匹配
              </cus-button>

                            </div>
                        </template>
            </cus-table>
            <div style="width: 100%; text-align: right">
              <cus-page  :data="pages2" class="mt_10" @pageChange="selectProductMaterialListApi()" :showSizer="false"
                :showElevator="false"></cus-page>
            </div>
          
        </div>
        <div class="contentBox-icon">
          <Icon type="md-swap" size="50"/>
        </div>
        <div class="contentBox-right" >
          <Form ref="formValidate" :model="bindProductForm" style="height: 100px;">
              <FormItem label="商品名称" prop="materialName" :label-width="80" style="margin-right: 20px">
                <Input v-model="bindProductForm.mealMaterialName" maxlength="20" clearable placeholder="请输入商品名" style="width: 150px">
                </Input>
              </FormItem>
              <FormItem label="商品类型:" prop="productCategoryId" :label-width="80" style="margin-right: 20px">
                <Select v-model="bindProductForm.productCategory" style="width: 150px" placeholder="请选择状态" clearable>
                  <Option
                :value="item.categoryName"
                v-for="(item, index) in productcategoryList"
                :key="index"
                >{{ item.categoryName }}</Option
              >
                </Select>
              </FormItem>
              
              <Button class="mr_20 mb_20" type="primary" @click="
             onSelsctBind
              ">查询</Button>
            </Form>
           <h4>已匹配列表</h4>
            <cus-table border :loading="loading3" :columns="columns3" :rowClassName="rowClassName" :data="showBindFoodList" :bottomClass="['cus-page','bottomButton']" :index="2">
              <template slot-scope="{ row }" slot="operation">
                            <div class="flex">
                   <cus-button
                type="text"
                size="small"
                :style="{ color: '#1E6FFF', padding: '0 8px' }"
                @onClick="onPriority(row)"
              >
                {{row.priority ? '优先采购' : '设置优先'}}
              </cus-button>
              <cus-button
                  type="text"
                  size="small"
                 @onClick="onCancelBind(row)"
                  :style="{
                    color: '#FF4746',
                    padding: '0 8px',
                  }"
                >
                  删除
                </cus-button>

                            </div>
                        </template>
            </cus-table>
            <div style="width: 100%; text-align: right">
              <cus-page  :data="pages3" class="mt_10" @pageChange="pages3.page = 1;" :showSizer="false"
                :showElevator="false"></cus-page>
            </div>
          
        </div>
      </div>
      <div class="bottomButton">

            <div style="margin-top: 20px; text-align: center" class="mr_20">
              <Button type="primary" @click="showAutoModal()">智能匹配</Button>
            </div>
            <div style="margin-top: 20px; text-align: center" class="mr_20">
              <Button @click="onClose()">关闭</Button>
            </div>
 
     
      </div>
      <autoModal ref="autoModal" :kitchenArea="kitchenArea" @onOk="onit"></autoModal>

  </div>
</template>

<script>
import {
  selectMealFoodOrPurchaseFoodMatching,
  selectProductMaterialList,
  saveFoodProductMatching,
  deleteFoodProductMatchingPriority,
  updateFoodProductMatchingPriority,
  
} from "@/api/organ/dishesModule";
import autoModal  from "./autoModal.vue";
const form = {
  type: 1, // 匹配类型
  mealMaterialName: "", // 食谱原料名
  materialName: "", // 商品名称
  foodClass: "",
};

export default {
  data() {
    return {
      ingredientsForm: form,
      noBindProductForm: {
        productCategoryId: '',
        materialName: '',
      },
      bindProductForm: {
        productCategory: '',
        mealMaterialName: '',
      },
      bindProductList: [],
      productList: [],
      ruleValidate: {},
      loading: false,
      loading2: false,
      loading3: false,
      areaList: this.$store.state.selectList.areaList, //区域
      specificationList: [],
      foodRuleTypeList: [],
      columns: [
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center",
        },
        {
          title: "食材类型",
          key: "foodClass",
          align: "center",
        },   
        {
          title: "食材名称",
          key: "materialName",
          align: "center",
        },
      ],
      columns2: [
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center",
        },
        {
          title: "商品类型",
          key: "productCategory",
          align: "center",
        
        },
        {
          title: "商品名称",
          key: "materialName",
          align: "center",
        
        },

        {
          title: "品牌",
          key: "brand",
          align: "center",
        
        },
        {
          title: "价格",
          key: "packagingPrice",
          align: "center",
       
        },
        {
          title: "计量单位",
          key: "packagingUtil",
          align: "center",
   
        },
        {
          title: "操作",
          slot: "operation",
          width: '70px',
          align: "center",
   
        },

      ],
      columns3: [
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center",
        },
        {
          title: "商品类型",
          key: "productCategory",
          align: "center",
        
        },
        {
          title: "商品名称",
          key: "productMaterialName",
          align: "center",
        
        },

        {
          title: "品牌",
          key: "brand",
          align: "center",
        
        },
        {
          title: "价格",
          key: "packagingPrice",
          align: "center",
       
        },
        {
          title: "计量单位",
          key: "packagingUtil",
          align: "center",
   
        },
        {
          title: "操作",
          slot: "operation",
          width: '120px',
          align: "center",
   
        },

      ],
      data: [],
      ingredientsData: [],
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      pages2: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      pages3: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      selectItem: null,
      step: 1,
      single: false,
    };
  },
  props: {
    kitchenArea: {
      type: [Number,String],
      default: ''
    },
    materialTypeList: {
      type: Array,
      default: () => []
    },
    productcategoryList: {
      type: Array,
      default: () => []
    }
  },
  components: {
  autoModal
},

  mounted() {
   this.onit()
  },
  computed: {
    showBindFoodList() {
      let newList = this.$cu.deepClone(this.bindProductList)
      newList.forEach(it => {
        if(it.priority) it.__highlight = true
      })
      Object.keys(this.bindProductForm).forEach(e => {
      	 // 调用自己定义好的筛选方法
         newList = filterFunc(this.bindProductForm[e], e, newList)
      })
    function  filterFunc(val, target, filterArr) {
     console.log(filterArr,'参数');
     console.log(val,'参数');
      // 参数不存在或为空时，就相当于查询全部
      if (val == undefined || val == '') return filterArr
      return filterArr.filter(p => p[target].indexOf(val) > -1) // 可以自己加一个.toLowerCase()来兼容一下大小
      
    }
    this.pages3.pageTotal = newList.length
    if(this.pages3.pageTotal > this.pages3.pageSize*this.pages3.page) {
      return newList.slice(this.pages3.pageSize*(this.pages3.page-1),this.pages3.pageSize*this.pages3.page)
    } else {
      return newList.slice(this.pages3.pageSize*(this.pages3.page-1),this.pages3.pageTotal)
    }
    }
   
  },
  methods: {
    onit() {
      console.log('初始化');
      
      this.ingredientsForm = this.$cu.deepClone(form);
    this.selectProductMaterialListApi()
    this.selectMealFoodOrPurchaseFoodMatchingApi()
    },
    // 关闭
    onClose() {
      this.$emit('onClose')
      
    },
    // 给特定的行添加类
    rowClassName(row, index) {
      console.log(row,'控制yanse');
      
      // 根据条件给特定行添加颜色
      if (row.priority) {
        return 'activeRow';
      }
      return '';
    },
    // 伪造一个查询
    onSelsctBind() {
     this.loading3 = true
     setTimeout(() => {
      this.loading3 = false
     },500)
    },
    onVisibleChange(v) {
      if (!v) {
        this.ingredientsForm = this.$cu.deepClone(form);
        this.selectItem = null;
        this.step = 1;
        this.single = false;
      }
    },
    // 智能匹配
    showAutoModal() {
     this.$refs['autoModal'].show()
    },
    onOk() {
      if (this.step == 1) {
        this.step = 2;
      }
      this.selectProductMaterialListApi();
    },
    // 点击匹配
    onMatching({materialId,materialName}) {
      if(this.selectItem) {
        this.saveFoodProductMatchingApi(materialId,materialName)
      } else {
       this.$Message.error('请选择要匹配的食材')
      }

    },
    // 左边选中列
    onCurrentChange(e) {
      this.selectItem = e
      this.noBindProductForm.materialName = e.materialName
      this.bindProductList = e.foodProductMatchingList
      this.selectProductMaterialListApi()
    },
    deepClone(obj) {
      obj
      let newObj = {}
     },
    // 优先采购
    onPriority(item) {
      console.log(item.priority == 0);
      
   if(item.priority == 0)   this.changePriority(item)
    },
  // 取消匹配
  onCancelBind(item) {
    this.cancelBind(item)
  },
    // 待绑定食材列表
    selectMealFoodOrPurchaseFoodMatchingApi(type=0) {
      this.loading = true;
      this.selectItem = null
      return new Promise((resolve) => {
        selectMealFoodOrPurchaseFoodMatching({
          type: this.ingredientsForm.type,
          kitchenArea: this.kitchenArea,
          mealMaterialName: this.ingredientsForm.mealMaterialName,
          foodClass: this.ingredientsForm.foodClass,
          current: this.pages.page,
          size: this.pages.pageSize,
        }).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.ingredientsData = res.data.list;
            if(type == 0) {
              this.ingredientsData[0]._highlight = true
            this.selectItem = this.ingredientsData[0]
            this.noBindProductForm.materialName = this.ingredientsData[0].materialName
            this.bindProductList = this.ingredientsData[0].foodProductMatchingList
            }else {
              this.ingredientsData.forEach(item => {
                if(item.materialId == this.selectItem.materialId) {
                  console.log('匹配');   
                  item._highlight = true
                  this.bindProductList = item.foodProductMatchingList
                }
              })
            }
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 商品列表
    selectProductMaterialListApi() {
      this.loading2 = true;
      return new Promise((resolve) => {
        selectProductMaterialList({
          materialName: this.noBindProductForm.materialName,
          kitchenArea: this.kitchenArea,
          current: this.pages2.page,
          size: this.pages2.pageSize,
          productCategoryId: this.noBindProductForm.productCategoryId
        }).then((res) => {
          this.loading2 = false;
          if (res.code === 1) {
            this.productList = res.data.list;
            this.pages2.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 绑定
    saveFoodProductMatchingApi(materialId,materialName) {
      this.loading = true;
      return new Promise((resolve) => {
        saveFoodProductMatching({
          foodProductMatchingId: this.selectItem.foodProductMatchingId,
          mealMaterialId: this.selectItem.materialId,
          mealMaterialName: this.selectItem.materialName,
          kitchenArea: this.kitchenArea,
          // 是否优先
          priority:  0,
          productMaterialId: materialId,
          productMaterialName: materialName,
        }).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$Message.success("匹配成功.");
            this.selectMealFoodOrPurchaseFoodMatchingApi(1);
            resolve();
          }
        });
      });
    },
    // 取消匹配
    cancelBind(item) {
      this.loading = true;
      return new Promise((resolve) => {
        deleteFoodProductMatchingPriority({
          foodProductMatchingId: item.foodProductMatchingId,
        }).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$Message.success("已取消匹配.");
            this.selectMealFoodOrPurchaseFoodMatchingApi(1);
            resolve();
          }
        });
      });
    },
    // 更改优先级
    changePriority(item) {
      this.loading = true;
      return new Promise((resolve) => {
        updateFoodProductMatchingPriority({
          mealMaterialId: item.mealMaterialId,
          foodProductMatchingId: item.foodProductMatchingId,
          supplyStatus: item.supplyStatus,
        }).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$Message.success("匹配优先级更换成功.");
            this.selectMealFoodOrPurchaseFoodMatchingApi(1);
            resolve();
          } else {
            item.priority = 0;
          }
        });
      });
    },
  },
};
</script>

<style scoped>
/deep/.ivu-select-multiple .ivu-select-selection .ivu-select-placeholder {
  /* height: 40px !important; */
  height: auto !important;
  line-height: 32px !important;
}

/deep/.ivu-select-selection {
  height: auto !important;
  min-height: 32px !important;
  border-radius: 2px !important;
}

/deep/.ivu-table-cell {
  padding-left: 0 !important;
  padding-right: 0 !important;
  padding-top: 0 !important;
  padding-bottom: 0 !important;
}

/deep/.ivu-table td {
  position: relative !important;
  
}
/deep/  .activeRow > .ivu-table-column-center {
    background-color: #80bffe !important;
}
</style>

<style scoped lang="less">
/deep/ .activeRow {

  background-color: #80bffe !important;
}
.location {
  position: absolute;
  top: 7px;
  left: 280px;
}
.contentBox {
  display: flex;
  justify-content: space-between;

  &-left {
    flex: 1.4;
    // width: 586px;
  }

  &-center {
    flex: 2;
    padding-left:40px;
    // padding: 0 40px;
  }
  &-icon {
    display: flex;
    align-items: center;
   
    padding:0 40px;
  }
  &-right {
    flex: 2
    // padding-left: 10px;
  }
}

.slotBox {
  width: 100%;

  // padding: 5px 0;
  &-item {
    padding: 10px 0;
    border-bottom: 1px solid #e3e8ee;
    min-height: 61px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.noBorderB {
  border-bottom: none !important;
}

.namebox {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-left: 2px solid white;
  cursor: pointer;
}

.selecteft {
  color: #1890ff;
  background: #e5f6ff;
  border-left: 2px solid #1890ff;
}

.chooseItem {
  line-height: 22px;
  padding: 4px 8px;
  border: 1px solid #e3e8ee;
  border-radius: 3px;
  background: white;
  text-align: center;
  word-break: break-all;
  font-size: 12px;
  width: 120px;
  min-height: 32px;
}
.bottomButton {
  display: flex;
  justify-content: end;
}


</style>
